package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.web.http.HttpContentType;
import com.ts.api.http.org.entity.apply.OrgApplyShangHaiChangShaWuHanXiaoHongShuZhiHu;
import com.ts.api.http.org.entity.dataexchange.OrgDataExchangeShangHaiChangShaWuHanXiaoHongShuZhiHu;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 *  上海 长沙 武汉小红书知乎
 *  @author 江小游
 */
@ApiPlan(productId = "205", type = ApiPlanConvertType.ORG_PHONE_MD5)
public class ApiOrgPhoneMd5ShangHaiChangShaWuHanXiaoHongShuZhiHu implements ApiOrgPhoneMd5ConvertHandler {

    private static final Integer APP_ID=105325;
    private static final String APP_KEY="1mUeJ373s3FfrHVyHG0P";
    private static final String VENDER_NAME="xhszh";
    private static final String CHANNEL="xhszh";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        apiDataExchangeParameter.setHttpContentType(HttpContentType.APPLICATION_FORM_URLENCODED);
        // 撞库流程
        OrgDataExchangeShangHaiChangShaWuHanXiaoHongShuZhiHu orgDataExchange = new OrgDataExchangeShangHaiChangShaWuHanXiaoHongShuZhiHu();
        //  赋值撞库属性
        orgDataExchange.setTel(apiDataExchangeParameter.getPhoneMd5());
        orgDataExchange.setCity(apiDataExchangeParameter.getCity().replace("市",""));
        // 随机数
        String noncestr=IdUtils.generateIdNumberStr();
        // 时间戳
        Integer time=(int) (System.currentTimeMillis()/1000L);
        Map<String, Object> params = new TreeMap<>(); // TreeMap 自动按 ASCII 排序
        params.put("appid", APP_ID);
        params.put("appkey", APP_KEY);
        params.put("city", orgDataExchange.getCity());
        params.put("noncestr",noncestr);
        params.put("timestamp",time);
        params.put("tel", orgDataExchange.getTel());
        String signature = generateSign(params);
        return MapUtils.newHashMap(newMap -> {
            newMap.put("appid", APP_ID);
            newMap.put("noncestr",noncestr);
            newMap.put("timestamp",time);
            newMap.put("tel", orgDataExchange.getTel());
            newMap.put("signature", signature);
        });
    }
    /**
     * 生成签名
     */
    // 生成签名的方法
    public static String generateSign(Map<String, Object> params) {
        // 按照字段名的ASCII码排序
        List<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        // 拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : sortedKeys) {
            // 拼接参数（key=value）
            stringBuilder.append(key).append("=").append(params.get(key)).append("&");
        }
        // 去掉最后的 '&' 符号
        stringBuilder.setLength(stringBuilder.length() - 1);
        // 进行 SHA-1 加密并返回签名
        return sha1(stringBuilder.toString());
    }

    // SHA-1 加密
    public static String sha1(String input) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            byte[] bytes = sha1.digest(input.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02x", b));
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 Algorithm not found", e);
        }
    }
    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getString("resStatus"), "1")) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        //  根据文档响应判断
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        apiApplyParameter.setHttpContentType(HttpContentType.APPLICATION_FORM_URLENCODED);
        //  进件流程-默认JSON发送如果需要别的方式，或者需要增加请求头，请看apiApplyMessage拓展方法
        OrgApplyShangHaiChangShaWuHanXiaoHongShuZhiHu orgApply = new OrgApplyShangHaiChangShaWuHanXiaoHongShuZhiHu();
        //  赋值进件属性
        orgApply.setVender_name(VENDER_NAME);
        // 通道名
        orgApply.setChannel(CHANNEL);
        // 用户名
        orgApply.setName(apiApplyParameter.getUserName());
        // 身份证
        orgApply.setIdcard(apiApplyParameter.getIdcard());
        //  城市/默认不带市
        orgApply.setCity(apiApplyParameter.getCity().replace("市",""));
        //  性别-要获取中文性别（男/女）使用apiFieldConverter.getSexText
        String sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", "男")
                .when("1", "女")
                .end();
        orgApply.setSex(sex);
        // 手机号
        orgApply.setTelphone(apiApplyParameter.getPhone());
        /*
           职业
           1.上班族
           2.自由职业
           3.企业主（有营业执照）
           4.公务员或事业单位
         */
        String career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", "工薪族")
                .when("2", "工薪族")
                .when("3", "小企业主")
                .when("4", "公务员")
                .when("5", "个体户")
                .end();
        orgApply.setVocation(career);
        // 生日
        orgApply.setBirthday(getBirthdayFromId(apiApplyParameter.getIdcard()));
        /*
          月收入
          1.1000-3000
          2.3000-8000
          3.8000~15000
          4.15000~30000
          5.30000以上
        */
        String salary = ChooseEq.create(apiApplyParameter.getMonthlySalary())
                .when("1", "1000-3000")
                .when("2", "3000-8000")
                .when("3", "8000-15000")
                .when("4", "15000-30000")
                .when("5", "30000以上")
                .end();
        orgApply.setSalary(salary);
        /*
           贷款金额
           1.3万以下
           2.5万-10万
           3.10万-20万
           4.20万以上
         */
        Integer loanAmount = ChooseEq.create(apiApplyParameter.getLoanAmount())
                .when("1", 3)
                .when("2", 10)
                .when("3", 20)
                .when("4", 40)
                .end();
        orgApply.setLoan_amount(loanAmount);
        // 贷款期限
        String loanTime = ChooseEq.create(apiApplyParameter.getLoanTerm())
                .when("1", "3")
                .when("2", "6")
                .when("3", "12")
                .when("4", "24")
                .when("5", "36")
                .when("6", "60")
                .end();
        orgApply.setLoan_time(loanTime);
        /*
          信用卡额度
          1.无信用卡
          2.3千以下
          3.3千-1万
          4.1-3万
          5.3万以上
          6.有信用卡
        */
        String creditLimit = ChooseEq.create(apiApplyParameter.getCreditLimit())
                .when("1", "N")
                .when("2", "Y")
                .when("3", "Y")
                .when("4", "Y")
                .when("5", "Y")
                .when("6", "Y")
                .end();
        orgApply.setHave_credit_card(creditLimit);
        /*
          我方字典-房产情况
          1.无房产
          2.有房不抵押
          3.有房可抵押
          4.有房产
          5.有按揭房产
          6.有全款房产
        */
        String realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                .when("1", "N")
                .when("2", "Y")
                .when("3", "Y")
                .when("4", "Y")
                .when("5", "Y")
                .when("6", "Y")
                .end();
        orgApply.setHave_house(realEstateInfo);
        /*
           我方字典-车辆情况
           1.无车产
           2.有车不抵押
           3.有车可抵押
           4.有车

         */
        String carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                .when("1", "N")
                .when("2", "Y")
                .when("3", "Y")
                .when("4", "Y")
                .end();
        orgApply.setHave_car(carInfo);
        /*
          社保缴纳
          1.无社保
          2.缴纳6个月以下
          3.缴纳6个月以上
          4.有社保
        */
        String socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                .when("1", "N")
                .when("2", "Y")
                .when("3", "Y")
                .when("4", "Y")
                .end();
        orgApply.setShebao(socialSecurity);
        /*
          公积金
          1.无公积金
          2.缴纳6个月以下
          3.缴纳6个月以上
          4.有公积金
        */
        String providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                .when("1", "N")
                .when("2", "Y")
                .when("3", "Y")
                .when("4", "Y")
                .end();
        orgApply.setHave_fund(providentFund);
        /*
            花呗额度
            1.无额度
            2.3千以下
            3.3千-1万
            4.1万-3万
            5.3万以上
         */
        String hbLimit = ChooseEq.create(apiApplyParameter.getHbLimit())
                .when("1", "N")
                .when("2", "Y")
                .when("3", "Y")
                .when("4", "Y")
                .when("5", "Y")
                .end();
        orgApply.setHave_ant_credit(hbLimit);
       /*
          工资发放形式/银行代发/打卡方式
          1.银行代发打卡
          2.现金收入
          3.个人转账
        */
        Integer salaryPayMethod = ChooseEq.create(apiApplyParameter.getSalaryPayMethod())
                .when("1", 1)
                .when("2", 3)
                .when("3", 2)
                .end();
        orgApply.setSalary_method(salaryPayMethod);
        // 备注
        orgApply.setRemark(apiApplyParameter.getFormRemark());
        // 随机数
        String noncestr=IdUtils.generateIdNumberStr();
        // 时间戳
        Integer time=(int) (System.currentTimeMillis()/1000L);
        Map<String,Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("appid",APP_ID);
            newMap.put("appkey",APP_KEY);
            newMap.put("timestamp",time);
            newMap.put("noncestr",noncestr);
            newMap.put("name", orgApply.getName());
            newMap.put("city", orgApply.getCity());
            newMap.put("telphone", orgApply.getTelphone());
            newMap.put("birthday", orgApply.getBirthday());
            newMap.put("vocation", orgApply.getVocation());
            newMap.put("salary", orgApply.getSalary());
            newMap.put("loan_amount", orgApply.getLoan_amount());
            newMap.put("loan_time", orgApply.getLoan_time());
            newMap.put("vender_name", orgApply.getVender_name());
            newMap.put("channel", orgApply.getChannel());
            newMap.put("idcard", orgApply.getIdcard());
            newMap.put("sex", orgApply.getSex());
            newMap.put("have_credit_card", orgApply.getHave_credit_card());
            newMap.put("have_house", orgApply.getHave_house());
            newMap.put("have_car", orgApply.getHave_car());
            newMap.put("shebao", orgApply.getShebao());
            newMap.put("have_fund", orgApply.getHave_fund());
            newMap.put("have_ant_credit", orgApply.getHave_ant_credit());
            newMap.put("salary_method", orgApply.getSalary_method());
            newMap.put("remark", orgApply.getRemark());
        });
        //  请求实体转换,默认JSON方式，如果FORM方式直接返回实体类，并且设置请求头为FORM表单
        String signature = generateSign(map);
        return MapUtils.<String, Object>newHashMap(newMap -> {
            newMap.put("appid",APP_ID);
            newMap.put("appkey",APP_KEY);
            newMap.put("timestamp",time);
            newMap.put("noncestr",noncestr);
            newMap.put("name", orgApply.getName());
            newMap.put("city", orgApply.getCity());
            newMap.put("telphone", orgApply.getTelphone());
            newMap.put("birthday", orgApply.getBirthday());
            newMap.put("vocation", orgApply.getVocation());
            newMap.put("salary", orgApply.getSalary());
            newMap.put("loan_amount", orgApply.getLoan_amount());
            newMap.put("loan_time", orgApply.getLoan_time());
            newMap.put("vender_name", orgApply.getVender_name());
            newMap.put("channel", orgApply.getChannel());
            newMap.put("idcard", orgApply.getIdcard());
            newMap.put("sex", orgApply.getSex());
            newMap.put("have_credit_card", orgApply.getHave_credit_card());
            newMap.put("have_house", orgApply.getHave_house());
            newMap.put("have_car", orgApply.getHave_car());
            newMap.put("shebao", orgApply.getShebao());
            newMap.put("have_fund", orgApply.getHave_fund());
            newMap.put("have_ant_credit", orgApply.getHave_ant_credit());
            newMap.put("salary_method", orgApply.getSalary_method());
            newMap.put("remark", orgApply.getRemark());
            newMap.put("signature", signature);
        });
    }
    public static String getBirthdayFromId(String idNumber) {
        if (idNumber == null || (!idNumber.matches("\\d{15}") && !idNumber.matches("\\d{17}[0-9X]"))) {
            throw new IllegalArgumentException("无效的身份证号码");
        }

        String birthDateStr;
        if (idNumber.length() == 18) {
            // 18位身份证：第7~14位为生日（yyyyMMdd）
            birthDateStr = idNumber.substring(6, 14);
        } else {
            // 15位身份证：第7~12位为生日（yyMMdd），补全为19yyMMdd
            birthDateStr = "19" + idNumber.substring(6, 12);
        }

        // 验证日期是否合法
        try {
            LocalDate.parse(birthDateStr, DateTimeFormatter.BASIC_ISO_DATE);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("生日日期无效: " + birthDateStr);
        }

        // 格式化为 yyyy-MM-dd
        return String.format("%s-%s-%s",
                birthDateStr.substring(0, 4),
                birthDateStr.substring(4, 6),
                birthDateStr.substring(6, 8));
    }
    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getString("resStatus"), "1")) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        //  根据文档响应判断
        return RespOrgPhoneMd5Apply.ofSuc();
    }
}
